﻿/*  
	------------------------------------------------------------------------
	 NQ Software Development Kit Component
	
	 Homepage: http://www.awzhome.de/
	------------------------------------------------------------------------
	
	This Source Code Form is subject to the terms of the Mozilla Public
	License, v. 2.0. If a copy of the MPL was not distributed with this
	file, You can obtain one at http://mozilla.org/MPL/2.0/.
   
	The Original Code is code of NQ Software Development Kit Component.

	The Initial Developer of the Original Code is Andreas Weizel.
	Portions created by the Initial Developer are
	Copyright (C) 2012 Andreas Weizel. All Rights Reserved.
	
	Contributor(s): (none)
	
	------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AWZhome.NQ.Core;
using AWZhome.NQsdk.Helpers;
using AWZhome.NQ.Core.Fluent;
using System.Globalization;

namespace AWZhome.NQsdk.Services
{
	[NQExportedService(SingleInstance = true)]
	public class SdkLogCacheService : ISdkLogCacheService
	{
		private List<LogMessage> _logMessageCache;
		private int _viewerCounter;
		private UInt64 _lastMessageID;
		private bool _cachingActive;

		public SdkLogCacheService()
		{
			_logMessageCache = new List<LogMessage>();
			_viewerCounter = 0;
			_cachingActive = true;

			// Event handler for log messages
			NQServiceManager.Instance.MessageLogged += NQServiceManager_MessageLogged;
		}

		public void RegisterViewer()
		{
			if (_viewerCounter == 0)
			{
				_cachingActive = false;
			}
			_viewerCounter++;
		}

		public void UnregisterViewer()
		{
			if (_viewerCounter > 0)
			{
				_viewerCounter--;
			}
			if (_viewerCounter == 0)
			{
				_cachingActive = true;
			}
		}

		public IList<LogMessage> FetchLogMessages()
		{
			// Copy the messages to new list to protect internal cache list
			List<LogMessage> fetchedLogCache = new List<LogMessage>(_logMessageCache);
			_logMessageCache.Clear();
			return fetchedLogCache;
		}

		private void NQServiceManager_MessageLogged(object sender, NQLogEventArgs e)
		{
			_lastMessageID++;

			if (_cachingActive)
			{
				if (_logMessageCache.Count > 5000)
				{
					// The cache is exhausted, we have to delete oldest message in it
					_logMessageCache.RemoveAt(0);
				}

				// Cache the message
				LogMessage message = new LogMessage()
				{
					MessageID = _lastMessageID,
					Level = e.LogType,
					Timestamp = e.Timestamp.ToShortDateString() + " " + e.Timestamp.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture),
					SourceService =
						(e.SourceService != null) ? ServiceCore.ObjectMetaInfo(e.SourceService).ServiceType.ToString() : "",
					Message = e.LogMessage
				};
				_logMessageCache.Add(message);
			}
		}
	}
}
